package com.tanhua.admin.service;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.db.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //登录
    public Map login(String username, String password, String code, String uuid) {
        //1、判断验证码是否一致
        String key = Constants.CAP_CODE+uuid;
        String value = redisTemplate.opsForValue().get(key);
        //2、如果不一致，抛出异常
        if(StringUtils.isEmpty(value) || !value.equals(code)) {
            throw new BusinessException("验证码不一致");
        }
        //3、如果一致，删除redis中的验证码数据
        redisTemplate.delete(key);
        //4、根据用户名查询管理员对象
        QueryWrapper<Admin> qw = new QueryWrapper<>();
        qw.eq("username",username);
        Admin admin = adminMapper.selectOne(qw);
        //5、判断管理员对象是否存在，数据库中的密码和输入的密码是否一致
        //对输入的密码进行加密之后，再比较
        password = SecureUtil.md5(password);
        if(admin == null || !admin.getPassword().equals(password)) {
            //6、对象不存在，或者密码不一致，抛出异常
            throw new BusinessException("用户名或者密码错误");
        }
        //7、生成Token
        Map map = new HashMap();
        map.put("id",admin.getId());
        map.put("username",admin.getUsername());
        String token = JwtUtils.getToken(map);
        //8、构造返回
        Map retMap = new HashMap();
        retMap.put("token",token);
        return retMap;
    }

    //根据id查询管理员对象
    public Admin findById(Long userId) {
        return adminMapper.selectById(userId);
    }
}
